<template>
  <van-nav-bar :left-arrow="false" title="首页" :fixed="true" @click-right="navToPage('/search')">
    <template #left>
      <van-image src="https://create.nightowl.top/static/images/logo.png" @click="logoClicked" height="40"
        width="40"></van-image>
    </template>
    <template #right><van-icon name="search" color="#29b3b1" /></template>
  </van-nav-bar>
  <div style="margin-top:40px;">
    <van-sticky offset-top="30px">
      <!-- <van-notice-bar color="#1989fa" background="#ecf9ff" left-icon="info-o" scrollable="true">
        项目已通过生产环境测试，目前为试运营阶段，讲不定期修复异常，希望您能够理解~
      </van-notice-bar> -->
      <van-tabs v-model:active="currentTabIndex" @change="changeTab">
        <van-tab :title="item.tag" v-for="item in groupList" v-bind:key="item.id" />
      </van-tabs>
    </van-sticky>
  </div>
  <!--分页渲染列表-->
  <div class="cloth-container" @scroll="pageScroll">
    <!--骨架屏列表-->
    <div v-if="isClothLoading">
      <van-skeleton :style="{ flexWrap: 'wrap' }">
        <template #template>
          <div class="cloth-skele-box" v-for="(item) in [1, 2, 3, 4, 5, 6]" :key="item">
            <div class="pre-img">
              <van-skeleton-image image-size="100%" />
            </div>
            <div class="pre-title">
              <van-skeleton-paragraph row-width="60%" />
              <van-skeleton-paragraph />
            </div>
          </div>
        </template>
      </van-skeleton>
    </div>
    <div v-else class="cloth-box">
      <div class="cloth-item" v-for="(item) in clothList" v-bind:key="item.cloth_id"
        @click="changeToDetail(item.cloth_id)">
        <div class="cloth-img"><van-image fit="contain" width="100%" height="100%" :src="item.cover" lazy-load /></div>
        <div class="cloth-title">{{ item.tag }}</div>
        <div class="cloth-price">￥{{ item.price.toFixed(1) }}<span>￥{{
          parseInt(item.price.toFixed(1) / item.discount).toFixed(1) }}</span></div>
        <div style="display:flex;align-items: center;justify-content: space-between;">
          <div class="cloth-discount"><span>{{ (item.discount * 10).toFixed(1) }}折优惠</span></div>
          <div class="want-buy">{{ item.likes }}人想买</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// @ is an alias to /src
import { showToast, showLoadingToast, showConfirmDialog } from "vant";
import { ref, onMounted, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import _service from "../request/axios";
const router = useRouter();
let currentPage = ref(1);
const limit = ref(10);
let groupList = ref([]);
let currentTabIndex = ref(0);
let clothList = ref([]);
let isClothLoading = ref(true);
let isTotal = ref(false);
let preTab = ref(0);
let isDataLoding = ref(false);
function logoClicked() {
  if (currentTabIndex.value == 0) {
    clothList.value = [];
    getClothList();
  }
}
function getClothList() {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  });
  isDataLoding.value = true;
  const params = {
    group: groupList.value[currentTabIndex.value].id,
    page: currentPage.value,
    limit: limit.value,
  };
  const token = localStorage.getItem("token");
  if (token) {
    params.userId = JSON.parse(localStorage.getItem("userInfo")).userId;
    params.recomIndex = localStorage.getItem("recomIndex");
  }
  _service.get("/cloth/index", {
    params: params
  }).then(res => {
    if (!res.code) {
      if (!clothList.value.length) clothList.value = res.data.list;
      else {
        clothList.value = clothList.value.concat(res.data.list);
      }
      isTotal.value = res.data.isTotal;
      isClothLoading.value = false;
      currentPage.value++;
      if (currentTabIndex.value == 0) {
        //写入推荐内容的扫描起始下标，避免重复
        localStorage.setItem("recomIndex", res.data.recomIndex);
      }
    } else {
      showToast(res.msg);
    }
    isDataLoding.value = false;
  })
}
function readClothStorage(key) {
  let tmpData = JSON.parse(localStorage.getItem(key));
  if (tmpData) {
    limit.value = tmpData.limit;
    currentPage.value = tmpData.currentPage;
    clothList.value = tmpData.clothList;
    isTotal.value = tmpData.isTotal;
    isClothLoading.value = false;
    return true;
  } else {
    limit.value = 10;
    currentPage.value = 1;
    clothList.value = [];
    return false;
  }
}
function changeToDetail(id) {
  router.push({
    path: '/detail/goods',
    query: {
      id
    }
  })
}
function changeTab(index) {
  //这里对上一次的数据进行一次缓存
  if (preTab.value != 0) {//记录推荐内容，如果是推荐那么不缓存数据
    localStorage.setItem(groupList.value[preTab.value].id + 'cloth', JSON.stringify({
      limit: limit.value,
      currentPage: currentPage.value,
      clothList: clothList.value,
      isTotal: isTotal.value
    }));
  }
  preTab.value = index;
  if (currentTabIndex.value == 0) {//推荐内容
    clothList.value = new Array();
    getClothList();
  } else {
    //非推荐内容
    groupList.value && readClothStorage(groupList.value[currentTabIndex.value].id + 'cloth') || getClothList();
  }
}
function pageScroll(e) {
  if (e.target.scrollTop + e.target.clientHeight + 10 > e.target.scrollHeight) {
    //重新发送请求，获取新一批衣服的数据
    if (!isTotal.value) {
      if (!isDataLoding.value) {
        getClothList();
      }
    } else {
      showToast({
        message: '再怎么找也没有啦~',
        wordBreak: 'break-word'
      });
    }
  }
}
function pageInit() {
  //处理登录提示弹出层
  let loginToast = localStorage.getItem("showLoginToast");
  let token = localStorage.getItem("token");
  if (!loginToast && !token) {
    localStorage.setItem("showLoginToast", true);
    showConfirmDialog({
      title: '温馨提示',
      message:
        '推荐你登录账号信息，这样系统能够更好地为您提供服务~',
    }).then(() => {
      navToPage("/login");
    }).catch(() => {
      console.log("用户取消登录操作！");
    });
  }
  _service.get("/cloth/sort").then(res => {
    if (!res.code) {
      groupList.value = res.data;
      groupList.value && readClothStorage(groupList.value[currentTabIndex.value].id + 'cloth') || getClothList();
    }
  });
}
function navToPage(route) {
  router.push({
    path: route
  })
}
onMounted(() => {
  pageInit();
})
onActivated(() => {
  //获取token探测
  if (groupList.value.length > 0) {
    const token = localStorage.getItem("token");
    if ((token != null && groupList.value[currentTabIndex.value].id != "999") || (token == null && groupList.value[currentTabIndex.value].id == "999")) {
      pageInit();
    }
  }
})
</script>
<style scoped>
.cloth-container {
  width: 100%;
  overflow: scroll;
  height: calc(100vh - 90px);
  padding-bottom: 30px;
}

.cloth-skele-box {
  float: left;
  width: 50%;
  box-sizing: border-box;
  margin-top: 10px;
}

.cloth-skele-box:nth-child(odd) {
  padding-left: 10px;
  padding-right: 5px;
}

.cloth-skele-box:nth-child(even) {
  padding-left: 5px;
  padding-right: 10px;
}

.cloth-skele-box .pre-img {
  height: 220px;
}

.cloth-skele-box .pre-title {
  margin-top: 10px;
}

.cloth-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  text-align: left;
}

.cloth-item {
  width: 50%;
  padding: 5px 8px 15px;
  box-sizing: border-box;
}

.cloth-title {
  margin-top: 6px;
  line-height: 20px;
  font-size: 14px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: 10px;
}

.cloth-price {
  color: #ff3029;
  font-weight: bold;
  font-size: 14px;
}

.cloth-price span {
  font-size: 12px;
  color: #a8abb8;
  font-weight: normal;
  margin-left: 4px;
  text-decoration: line-through;
}

.cloth-discount span {
  background-color: #fde7e4;
  color: #fe605a;
  font-size: 12px;
  margin: 3px 0px;
  padding: 2px 4px;
}

.want-buy {
  font-size: 12px;
  color: #b4b4b4;
}
</style>